<template>
  <div class="todo-wrapper">
    <div v-if="!isEdit" class="title">{{ todo.content }}</div>
    <textarea v-else v-model="todo.content" class="title"></textarea>
    <div class="btn-wrapper">
      <van-button
        type="primary"
        size="large"
        @click="editTodo(`${isEdit ? 'save' : 'edit'}`)"
        >{{ isEdit ? "保存" : "编辑" }}</van-button
      >
      <van-button type="danger" @click="delTodo" size="large">删除</van-button>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import { Dialog, Toast } from "vant";
import pic1 from "../assets/temp/1.webp";
import pic2 from "../assets/temp/2.webp";
import pic3 from "../assets/temp/3.webp";
import pic4 from "../assets/temp/4.webp";
import pic5 from "../assets/temp/5.jpg";

export default {
  name: "Todo",
  data() {
    return {
      bannerData: [pic1, pic2, pic3, pic4, pic5],
      isEdit: false,
      ID: null,
      todo: {
        content: ""
      }
    };
  },
  created() {
    this.ID = this.$route.params.todoid;
    axios({
      method: "GET",
      url: `https://api.yizhanketang.cn/api/v1/todos/${this.ID}`
    }).then(res => {
      const { data } = res.data;
      this.todo = data;
    });
  },
  methods: {
    editTodo(opt) {
      this.isEdit = true;
      // console.log(opt)
      if (opt === "save") {
        // console.log(this.todo.content)
        // this.isEdit = false
        axios({
          method: "POST",
          url: `https://api.yizhanketang.cn/api/v1/todos/${this.ID}`,
          data: {
            content: this.todo.content
          }
        }).then(res => {
          Toast.success("修改成功!");
          const { data } = res.data;
          this.todo = data;
          this.isEdit = false;
        });
      }
    },
    delTodo() {
      Dialog.confirm({
        title: "提示",
        message: "你确定要删除此项吗？"
      }).then(() => {
        axios({
          method: "POST",
          url: `https://api.yizhanketang.cn/api/v1/todos/${this.ID}/delete`
        }).then(() => {
          this.$router.replace({
            name: "Home",
            query: {
              from: "todo"
            }
          });
        });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.todo-wrapper {
  padding: 0.2rem;

  .banner-item {
    height: 4rem;
    background: no-repeat center / cover;
  }

  .title {
    height: 3rem;
    width: 100%;
    border: 1px solid #1595ff;
    border-radius: 0.1rem;
    padding: 0.2rem;
    box-sizing: border-box;
  }

  .btn-wrapper {
    display: flex;
    margin-top: 0.2rem;

    > a {
      width: 45%;
      margin-right: 0.1rem;
      height: 0.8rem;
      line-height: 0.8rem;
      text-align: center;
      color: #fff;

      &:first-child {
        background-color: #1595ff;
      }

      &:last-child {
        background-color: #f00;
      }
    }
  }
}
</style>
